#include "contactuserlist.h"
#include "grouptipitem.h"
#include <QRandomGenerator>
#include "tcpmgr.h"
#include "usermgr.h"
#include <QTimer>
#include <QCoreApplication>
ContactUserList::ContactUserList(QWidget *parent):QListWidget(parent),_load_pending(false)
{
    Q_UNUSED(parent);
     this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
     this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    // 安装事件过滤器
     this->viewport()->installEventFilter(this);

    //模拟从数据库或者后端传输过来的数据,进行列表加载
    addContactUserList();

    connect(this,&QListWidget::itemClicked,this,&ContactUserList::slot_item_click);
    //对方同意后发给我添加 sig_add_auth_friend
    connect(TcpMgr::GetInstance().get(), &TcpMgr::sig_add_auth_friend,this,
            &ContactUserList::slot_add_auth_firend);

    //我同意对方后添加 sig_auth_rsp
    connect(TcpMgr::GetInstance().get(),&TcpMgr::sig_auth_rsp,this,&ContactUserList::slot_auth_rsp);
}

void ContactUserList::ShowRedPoint(bool bshow)
{
    _add_friend_item->ShowRedPoint(bshow);
}

bool ContactUserList::eventFilter(QObject *watched, QEvent *event)
{
    // 检查事件是否是鼠标悬浮进入或离开
    if (watched == this->viewport()) {
        if (event->type() == QEvent::Enter) {
            // 鼠标悬浮，显示滚动条
            this->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
        } else if (event->type() == QEvent::Leave) {
            // 鼠标离开，隐藏滚动条
            this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
        }
    }
    // 检查事件是否是鼠标滚轮事件
    if (watched == this->viewport() && event->type() == QEvent::Wheel) {
        QWheelEvent *wheelEvent = static_cast<QWheelEvent*>(event);
        int numDegrees = wheelEvent->angleDelta().y() / 8;
        int numSteps = numDegrees / 15; // 计算滚动步数
        // 设置滚动幅度
        this->verticalScrollBar()->setValue(this->verticalScrollBar()->value() - numSteps);
        // 检查是否滚动到底部
        QScrollBar *scrollBar = this->verticalScrollBar();
        int maxScrollValue = scrollBar->maximum();
        int currentValue = scrollBar->value();
        //int pageSize = 10; // 每页加载的联系人数量
        if (maxScrollValue - currentValue <= 0) {
            auto b_loaded = UserMgr::GetInstance()->IsLoadChatFin();
            if(b_loaded){
                return true;
            }

            if(_load_pending){
                return true;
            }

            _load_pending = true;

            QTimer::singleShot(100, [this](){
                _load_pending = false;
                QCoreApplication::quit(); // 完成后退出应用程序
                });
            // 滚动到底部，加载新的联系人
            qDebug()<<"load more contact user";
            //发送信号通知聊天界面加载更多聊天内容
            emit sig_loading_contact_user();
         }
        return true; // 停止事件传递
    }

    return QListWidget::eventFilter(watched, event);
}
std::vector<QString> heads2 = {
    ":/res/1.png",
    ":/res/2.png",
    ":/res/3.png",
    ":/res/4.png",
    ":/res/5.png"
};
std::vector<QString>  strs2 ={"hello world !",
                             "nice to meet u",
                             "New year，new life",
                            "You have to love yourself",
                            "My love is written in the wind ever since the whole world is you"};

std::vector<QString> names2 = {
    "llfc",
    "zack",
    "golang",
    "cpp",
    "java",
    "nodejs",
    "python",
    "rust"
};
void ContactUserList::addContactUserList()
{
    //------------设置好友验证框和联系人type
    auto* group = new GroupTipItem();
    auto *item = new QListWidgetItem;
    item->setSizeHint(group->sizeHint());
    this->addItem(item);
    this->setItemWidget(item, group);
    item->setFlags(item->flags() & Qt::ItemIsSelectable);

    _add_friend_item = new ConUserItem();
    _add_friend_item->setObjectName("new_friend_item");
    _add_friend_item->SetInfo(0,tr("新的朋友"),":/res/add_friend.png");
    _add_friend_item->SetItemType(ListItemType::ApplyfriendItem);

    //测试
    QListWidgetItem *add_item = new QListWidgetItem;
    //qDebug()<<"chat_user_wid sizeHint is " << chat_user_wid->sizeHint();
    add_item->setSizeHint(_add_friend_item->sizeHint());
    this->addItem(add_item);
    this->setItemWidget(add_item, _add_friend_item);
    //默认设置新的朋友申请条目被选中
    this->setCurrentItem(add_item);

    auto * groupCon = new GroupTipItem();
    groupCon->setGroupTip(tr("联系人"));
    _groupitem = new QListWidgetItem;
    _groupitem->setSizeHint(groupCon->sizeHint());
    this->addItem(_groupitem);
    this->setItemWidget(_groupitem, groupCon);
    _groupitem->setFlags(_groupitem->flags() & ~Qt::ItemIsSelectable);

    auto con_list = UserMgr::GetInstance()->GetConListPerPage();
    for(auto & con_ele : con_list){
        auto *con_user_wid = new ConUserItem();
        con_user_wid->SetInfo(con_ele->_uid,con_ele->_name, con_ele->_icon);
        QListWidgetItem *item = new QListWidgetItem;
        //qDebug()<<"chat_user_wid sizeHint is " << chat_user_wid->sizeHint();
        item->setSizeHint(con_user_wid->sizeHint());
        this->addItem(item);
        this->setItemWidget(item, con_user_wid);
    }

    UserMgr::GetInstance()->UpdateContactLoadedCount();

    // 测试测试
    for(int i = 0; i < 13; i++){
        int randomValue = QRandomGenerator::global()->bounded(100); // 生成0到99之间的随机整数
        int str_i = randomValue%strs2.size();
        int head_i = randomValue%heads2.size();
        int name_i = randomValue%names2.size();
        auto *con_user_wid = new ConUserItem();
        con_user_wid->SetInfo(0,names2[name_i], heads2[head_i]);
        QListWidgetItem *item = new QListWidgetItem;
        item->setSizeHint(con_user_wid->sizeHint());
        this->addItem(item);
        this->setItemWidget(item, con_user_wid);
    }
}

void ContactUserList::slot_item_click(QListWidgetItem *item)
{
    QWidget *widget = this->itemWidget(item); // 获取自定义widget对象
    if(!widget){
        qDebug()<< "slot item clicked widget is nullptr";
        return;
    }
    // 对自定义widget进行操作， 将item 转化为基类ListItemBase
    ListItemBase *customItem = qobject_cast<ListItemBase*>(widget);
    if(!customItem){
        qDebug()<< "slot item clicked widget is nullptr";
        return;
    }
    auto itemType = customItem->GetItemType();
    if(itemType == ListItemType::InvalidItem
            || itemType == ListItemType::GroupTypeItem){
        qDebug()<< "slot invalid item clicked ";
        return;
    }
   if(itemType == ListItemType::ApplyfriendItem){
       // 创建对话框，提示用户
       qDebug()<< "apply friend item clicked ";
       //跳转到好友申请界面
       emit sig_switch_apply_friend_page();
       return;
   }
   if(itemType == ListItemType::ContactUserItem){
       // 创建对话框，提示用户
       qDebug()<< "contact user item clicked ";
       //跳转到好友申请界面
       //auto item = std::dynamic_cast<ConUserItem*>(customItem);
       auto item = qobject_cast<ConUserItem*>(customItem);
       auto userinfo = item->GetInfo();
       emit sig_switch_friend_info_page(userinfo);
       return;
   }
}

void ContactUserList::slot_auth_rsp(std::shared_ptr<AuthRsp> authrsp)
{
    qDebug()<<"slot auth rsp";
    //是否已经为好友
    bool a = UserMgr::GetInstance()->CheckFriend(authrsp->_uid);
    if(a) return;

    auto *con_user_wid = new ConUserItem();
    con_user_wid->SetInfo(authrsp);
    QListWidgetItem *item = new QListWidgetItem;
    item->setSizeHint(con_user_wid->sizeHint());
    //this->addItem(item); 要显示在最上面

    // 获取 groupitem 的索引
    int index = this->row(_groupitem);
    // 在 groupitem 之后插入新项
    this->insertItem(index + 1, item);

    this->setItemWidget(item, con_user_wid);
}

void ContactUserList::slot_add_auth_firend(std::shared_ptr<AuthInfo> authinfo)
{
    qDebug()<<"slot add auth friend";
    //是否已经为好友
    bool a = UserMgr::GetInstance()->CheckFriend(authinfo->_uid);
    if(a) return;

    auto *con_user_wid = new ConUserItem();
    con_user_wid->SetInfo(authinfo);
    QListWidgetItem *item = new QListWidgetItem;
    item->setSizeHint(con_user_wid->sizeHint());

    // 获取 groupitem 的索引
    int index = this->row(_groupitem);
    // 在 groupitem 之后插入新项
    this->insertItem(index + 1, item);

    this->setItemWidget(item, con_user_wid);
}
